<template>
	<el-container>
		<!--		<el-header style="height: auto;">-->
		<!--			<sc-select-filter :data="filterData"-->
		<!--							  :label-width="80" @on-change="filterChange"></sc-select-filter>-->
		<!--		</el-header>-->
		<el-header style="height: auto;">
			<sc-select-filter
				:data="filterData"
				:label-width="80"
				@on-change="filterChange"
			></sc-select-filter>
		</el-header>
		<el-main class="nopadding" v-show="isVisible" >
			<scTable ref="table" :apiObj="apiObj" row-key="recordId" @selection-change="selectionChange" stripe
					 remoteSort remoteFilter>
				<el-table-column type="selection" width="50"></el-table-column>
<!--				<el-table-column label="#" type="index" width="50"></el-table-column>-->
				<el-table-column label="流水号" prop="id" width="100"></el-table-column>

				<el-table-column label="申请人" prop="userName" width="100"></el-table-column>
				<el-table-column label="申请人部门" prop="deptName" width="150"></el-table-column>
				<el-table-column label="审批人" prop="approverName" width="150"></el-table-column>
				<el-table-column label="审批人部门" prop="approverDeptName" width="150"></el-table-column>
				<el-table-column label="最后工作日" prop="factTime" width="150"></el-table-column>
				<el-table-column label="离职原因" prop="leaveCondition" width="150"></el-table-column>
				<el-table-column label="状态" prop="typeStatus">
					<template #default="scope">
						<span v-if="scope.row.typeStatus === '0'">审核中</span>
						<span v-else-if="scope.row.typeStatus === '1'">通过</span>
						<span v-else-if="scope.row.typeStatus === '2'">驳回</span>
						<span v-else-if="scope.row.typeStatus === '3'">初始化</span>
						<span v-else-if="scope.row.typeStatus === '99'">撤销</span>
					</template>
				</el-table-column>
			</scTable>
		</el-main>
		<el-main class="nopadding" v-show="isVisible1" >
			<scTable ref="table" :apiObj="apiObj" row-key="recordId" @selection-change="selectionChange" stripe
					 remoteSort remoteFilter>
				<el-table-column type="selection" width="50"></el-table-column>
				<!--				<el-table-column label="#" type="index" width="50"></el-table-column>-->
				<el-table-column label="流水号" prop="correlationId" width="100"></el-table-column>

				<el-table-column label="申请人" prop="applicantName" width="100"></el-table-column>
				<el-table-column label="申请人部门" prop="applicantDeptName" width="150"></el-table-column>
				<el-table-column label="审批人" prop="approverName" width="150"></el-table-column>
				<el-table-column label="审批人部门" prop="approverDeptName" width="150"></el-table-column>
				<el-table-column label="最后工作日" prop="hisLeaveRecord.factTime" width="150"></el-table-column>
				<el-table-column label="离职原因" prop="hisLeaveRecord.leaveCondition" width="150"></el-table-column>
				<el-table-column label="状态" prop="stats">
					<template #default="scope">
						<span v-if="scope.row.stats === '0'">审核中</span>
						<span v-else-if="scope.row.stats === '1'">通过</span>
						<span v-else-if="scope.row.stats === '2'">驳回</span>
						<span v-else-if="scope.row.stats === '3'">初始化</span>
						<span v-else-if="scope.row.stats === '99'">撤销</span>
					</template>
				</el-table-column>
				<el-table-column label="电子签名" align="center">
					<template v-slot="scope">
						<div v-if="scope.row.signatureUrl">
							<el-image
								style="width: 80px; height: 40px; cursor: pointer"
								:src="scope.row.signatureUrl"
								:preview-src-list="[scope.row.signatureUrl]"
								fit="contain"
								close-on-click-modal
								preview-teleported
								:z-index="9999"
							>
							</el-image>
						</div>
						<span v-else class="unsigned-text">未签署</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" fixed="right" align="right" width="170">
					<template #default="scope">
						<el-button-group>
							<el-button text type="primary" size="small" v-if="scope.row.stats === '0'" @click="openApprovalDialog(scope.row)">审批</el-button>
						</el-button-group>
					</template>
				</el-table-column>
			</scTable>
		</el-main>
	</el-container>
	<save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSaveSuccess"
				 @closed="dialog.save=false"></save-dialog>
	<recordDetails v-if="dialog.detailsSave" ref="detailsDialog" @closed="dialog.detailsSave=false"></recordDetails>
	<!-- 新增审批弹窗 -->
	<el-dialog v-model="approvalDialogVisible" title="审批" width="40%">
		<el-form :model="approvalFormData" label-width="100px">
			<el-form-item label="审批结果">
				<el-radio-group v-model="approvalFormData.stats">
					<el-radio label="1">同意</el-radio>
					<el-radio label="2">拒绝</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="备注">
				<el-input v-model="approvalFormData.remark" type="textarea" :rows="4"></el-input>
			</el-form-item>
			<div>
				<spersonalFinance
					ref="signaturePad"
					:line-width="4"
					:line-color="'#409EFF'"
					@save="handleSave"
					@error="handleError"
					@reset="reset"
				></spersonalFinance>
			</div>
		</el-form>
		<template #footer>
			<el-button @click="approvalDialogVisible = false">取消</el-button>
			<el-button type="primary" @click="submitApproval">提交</el-button>
		</template>
	</el-dialog>
</template>

<script>
import selectHrUserDialog from "@/views/module/selectHrUserDialog";
import scSelectFilter from '@/components/scSelectFilter'
import recordDetails from './details'
import saveDialog from './save'
import spersonalFinance from '@/components/scpersonalFinance/index.vue'
import { FINANCE_CODES } from '@/config/statusCodes'
export default {
	name: 'Hr User Leave Manage',
	components: {
		spersonalFinance,
		saveDialog,
		scSelectFilter,
		recordDetails,
		selectHrUserDialog
	},
	data() {
		return {
			resultImg:'',
			approvalDialogVisible: false, // 控制审批弹窗显示
			approvalFormData: {},
			currentRow: null, // 当前行数据
			isVisible: true,
			isVisible1: false,
			dialog: {
				save: false,
				detailsSave: false,
			},
			filterData: [
				{
					title: "角色",
					key: "role",
					multiple: false,
					options: [
						{label: "申请人", value: 1},
						{label: "审批人", value: 2}
					]
				}
			],

			// apiObj: this.$API.hr.hrLeave.HrTurnoverByApplicantId,
			apiObj: null,
			selection: [],
			search: {
				userId: '',
				date: '',
				leaveType: '',
			},
			tableData: [] // 添加 tableData
		}
	},
	mounted() {
		this.getHrTurnoverByApplicantId();
	},
	methods: {
		reset(){
			this.resultImg = ''
		},
		// 处理签名保存
		handleSave({ base64, file }) {
			// 自定义上传逻辑
			const formData = new FormData()
			formData.append('file', file)
			formData.append('code', FINANCE_CODES.RESIGN)
			this.$API.office.personalFinance.uploadFileByCode.post(formData)
				.then(res => {
					this.resultImg  = res.redirect
				})
				.catch(err => {
					this.$message.error('文件上传失败')
				})
		},
		// 处理错误
		handleError(message) {
			this.$message.error(message)
		},
		async batch_del() {
			await this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, '提示', {
				type: 'warning'
			}).then(async () => {
				var recordIdArr = [];
				for (var i = 0; i < this.selection.length; i++) {
					recordIdArr.push(this.selection[i].recordId);
				}
				const loading = this.$loading();
				var res = await this.$API.hr.hrReinstatement.deleteHrReinstatementByIds.post({ids: recordIdArr});
				if (res.code == 200) {
					this.$refs.table.refresh()
					this.$message.success(res.message)
				} else {
					this.$alert(res.message, "提示", {type: 'error'})
				}
				loading.close();
			}).catch(() => {

			})
		},

		createRecord() {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open()
			})
		},
		// async getSysDicByCode(){
		// 	var res = await this.$API.hr.hrDic.getHrDicByCode.get({code:'leaveType'});
		// 	if (res.code == 200) {
		// 		this.filterData[1].options=this.filterData[1].options.concat(res.data);
		// 	} else {
		// 		this.$alert(res.message, "提示", {type: 'error'})
		// 	}
		// },

		filterChange: function (value) {
			if (value.role === '1') {
				this.isVisible = true;
				this.isVisible1 = false;

				this.getHrTurnoverByApplicantId();

			} else if (value.role === '2'){
				this.isVisible = false;
				this.isVisible1 = true;
				this.getTurnoverByApprover();
			}
		},
		//添加
		getHrTurnoverByApplicantId: function () {
			const userInfo = this.$TOOL.data.get("USER_INFO");
			this.apiObj = {
				get: async (params) => {
					// 合并固定参数（userInfo.id）和动态参数（this.search）
					const mergedParams = {
						option1: userInfo.id,
						...this.search,
						...params // 允许外部传入的params覆盖默认值
					};
					const res =	await this.$API.hr.hrLeave.HrTurnoverByApplicantId.get(mergedParams);
					this.tableData = res.data; // 更新 tableData
					return res;
				}
			};
		},
		//编辑
		getTurnoverByApprover: function () {
			const userInfo = this.$TOOL.data.get("USER_INFO");
			this.apiObj = {
				get: async (params) => {
					// 合并固定参数（userInfo.id）和动态参数（this.search）
					const mergedParams = {
						option2: userInfo.id,
						...this.search,
						...params // 允许外部传入的params覆盖默认值
					};
					const res = await this.$API.hr.hrLeave.TurnoverByApprover.get(mergedParams);
					this.tableData = res.data; // 更新 tableData
					return res;
				}
			};
		},
		openApprovalDialog(row) {
			this.currentRow = row;
			this.approvalDialogVisible = true;
			this.approvalFormData.stats = '';
			this.approvalFormData.remark = '';
			if (this.$refs.signaturePad) {
				this.$refs.signaturePad.handleReset();
			}
		},
		submitApproval() {
			if (!this.approvalFormData.stats) {
				this.$message.error('请选择审批结果');
				return;
			}
			// 提交审批逻辑
			let params = {
				correlationId: this.currentRow.correlationId,
				stats: this.approvalFormData.stats,
				remark: this.approvalFormData.remark,
				signatureUrl:this.resultImg
			};
			// this.approvalFormData.id = this.currentRow.id;
			this.$API.hr.hrLeave.ApproveHrTurnover.get(params).then(res => {
				this.$refs.signaturePad.handleReset();
				this.$message.success('审批成功');
				this.approvalDialogVisible = false;
				this.getTurnoverByApprover();
			}).catch(err => {
				this.$refs.signaturePad.handleReset();
				this.$message.error('审批失败');
				console.error("接口调用失败", err);
			});
		},


		//查看
		handleSaveSuccess() {
			this.$refs.table.refresh()
		},
		//删除
		selectionChange(selection) {
			this.selection = selection;
		},
		//批量删除
		async table_del(row) {
			var reqData = {recordId: row.recordId}
			var res = await this.$API.hr.hrReinstatement.deleteHrReinstatement.post(reqData);
			if (res.code == 200) {
				this.$refs.table.refresh()
				this.$message.success("删除成功")
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		//表格选择后回调事件
		table_edit(row) {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('edit').setData(row)
			})
		},
		//搜索
		table_show(row) {
			this.dialog.detailsSave = true
			this.$nextTick(() => {
				this.$refs.detailsDialog.open('setting').setData(row)
			})
		},
		//本地更新数据
		async upsearch() {
			this.$refs.table.upData(this.search)
		}
	}
}
</script>

<style>
</style>
